const userModel = require("../models/userModel");

const sign = async (req, res) => {
    const query = { userName: req.body.userName }
    const findResult = await userModel.find(query)
    if (!findResult.length) {
        let saveResult = await userModel.save(req.body)
        console.log(saveResult)
        if (saveResult) {
            res.send({ status: true, msg: "注册成功" })
        }
    } else (
        res.send({ status: false, msg: "该用户名已经注册" })
    )
}


//实现保持用户登入状态

//声明一个构造函数
function UserInfo(userName, password, nickName) {
    this.userName = userName;
    this.password = password;
    this.nickName = nickName;
}

const login = async (req, res) => {
    if (req.session.userInfo) {
        const nickName = req.session.userInfo.nickName
        const userName = req.session.userInfo.userName
        res.send({ status: true, msg: nickName + "不要重复登入", nickName, userName })
        return
    }
    console.log(req.body)
    let query = { userName: req.body.userName, password: req.body.password }
    const findResult = await userModel.find(query)
    console.log(findResult)
    if (findResult.length) {
        const user = findResult[0];
        const userInfo = new UserInfo(user.userName, user.password, user.nickName)
        //挂载到sessin上面
        req.session.userInfo = userInfo;
        // console.log(req.session)
        //定义一个键值对 返回给前端的信息
        const info = {
            userName: req.session.userInfo.userName,
            nickName: req.session.userInfo.nickName
        }
        res.send({ status: true, msg: "登入成功", info })
    } else (
        res.send({ status: false, msg: "账户名密码错误" })
    )
}

const isLogin = async (req, res) => {
    // 用session里面的账号密码和数据库里面做匹配
    if (req.session.userInfo) {
        const Info = req.session.userInfo;
        console.log(Info)
        const query = { userName: Info.userName, password: Info.password };
        const veryResult = await userModel.find(query);
        if (veryResult.length) {
            res.send({ status: true, msg: "你已经登录过了" + Info.nickName, nickName: Info.nickName })
        }
    } else {
        res.send({ status: false, msg: "未登入" })
    }

}

const quit = (req, res) => {
    req.session.destroy();
    console.log(req.session)
    res.send({ status: true, meg: "退出成功" })
}

module.exports = {
    sign,
    login,
    isLogin,
    quit
}
